package handler

import (
	v1 "docker-api/api/v1"
	"docker-api/internal/service"
	"github.com/gin-gonic/gin"
	"net/http"
)

type DockerImagesHandler struct {
	*Handler
	dockerImagesService service.DockerImagesService
}

func NewDockerImagesHandler(
	handler *Handler,
	dockerImagesService service.DockerImagesService,
) *DockerImagesHandler {
	return &DockerImagesHandler{
		Handler:             handler,
		dockerImagesService: dockerImagesService,
	}
}

func (h *DockerImagesHandler) List(ctx *gin.Context) {
	images, err := h.dockerImagesService.List(ctx)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, v1.ErrBadRequest, nil)
		return
	}
	v1.HandleSuccess(ctx, images)
}

func (h *DockerImagesHandler) Pull(ctx *gin.Context) {
	var params struct {
		ImageName string `json:"imageName" binding:"required"`
	}
	if err := ctx.ShouldBindJSON(&params); err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, v1.ErrBadRequest, nil)
		return
	}

	err := h.dockerImagesService.Pull(ctx, params.ImageName)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, v1.ErrBadRequest, nil)
		return
	}
	v1.HandleSuccess(ctx, nil)
}

func (h *DockerImagesHandler) Delete(ctx *gin.Context) {
	var params struct {
		ImageId string `json:"imageId" binding:"required"`
	}
	if err := ctx.ShouldBindJSON(&params); err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, v1.ErrBadRequest, nil)
		return
	}

	err := h.dockerImagesService.Delete(ctx, params.ImageId)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, v1.ErrBadRequest, nil)
		return
	}
	v1.HandleSuccess(ctx, nil)
}

func (h *DockerImagesHandler) Import(ctx *gin.Context) {
	var params struct {
		Path string `json:"path" binding:"required"`
	}
	if err := ctx.ShouldBindJSON(&params); err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, v1.ErrBadRequest, nil)
		return
	}

	err := h.dockerImagesService.Import(ctx, params.Path)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, v1.ErrBadRequest, nil)
		return
	}
	v1.HandleSuccess(ctx, nil)
}

func (h *DockerImagesHandler) Tag(ctx *gin.Context) {
	var params struct {
		ImageId string `json:"imageId" binding:"required"`
		NewTag  string `json:"newTag" binding:"required"`
		NewName string `json:"newName" binding:"required"`
	}
	if err := ctx.ShouldBindJSON(&params); err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, v1.ErrBadRequest, nil)
		return
	}

	err := h.dockerImagesService.Tag(ctx, params.ImageId, params.NewTag, params.NewName)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, v1.ErrBadRequest, nil)
		return
	}
	v1.HandleSuccess(ctx, nil)
}

// Refresh 刷新，即为获取系统最新的镜像列表的进行存储和更新
func (h *DockerImagesHandler) Refresh(ctx *gin.Context) {
	err := h.dockerImagesService.Refresh(ctx)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, v1.ErrBadRequest, nil)
		return
	}
	v1.HandleSuccess(ctx, nil)
}
